import {
  ConflictException,
  BadRequestException,
  Injectable,
} from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { Repository } from 'typeorm';
import { AuthEntity } from './entities/auth.entity';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcryptjs from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';
import { RedisService } from '../redis/redis.service';
@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(AuthEntity) // 引入数据库连接
    private authRepository: Repository<AuthEntity>,
    private readonly jwtService: JwtService,
    private readonly redisService: RedisService, // 注册redis
  ) { }

  // 注册
  async signup(signupData: CreateAuthDto) {
    const findUser = await this.authRepository.findOne({
      where: { username: signupData.username },
    });
    if (findUser && findUser.username === signupData.username) {
      throw new ConflictException('用户已存在');
    }
    // 对密码进行加密
    signupData.password = bcryptjs.hashSync(signupData.password, 10);
    const newUser = await this.authRepository.save(signupData);

    // 将新用户存入redis
    await this.redisService.set(
      `user:${newUser.username}`,
      JSON.stringify(newUser),
    );

    return {
      msg: '注册成功',
    };
  }

  // 登录
  async login(loginData: CreateAuthDto) {
    let userString = await this.redisService.get(`user:${loginData.username}`);

    console.log(userString);
    const findUser = await this.authRepository.findOne({
      where: { username: loginData.username },
    });
    if (!findUser) return new BadRequestException('用户不存在');

    const compareRes: boolean = bcryptjs.compareSync(
      loginData.password,
      findUser.password,
    );

    if (!compareRes) return new BadRequestException('密码错误');
    const payload = { username: findUser.username };

    return {
      access_token: this.jwtService.sign(payload),
      msg: '登录成功',
    };
  }
}
